package com.library.Book.controller;

import com.library.Book.model.Book;
import com.library.Book.model.BookExample;
import com.library.Book.service.BookService;

import java.util.*;

import com.library.Publish.model.Publish;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
public class BookController {
    
    private BookService bookService;

    //通过构造器注入service
    @Autowired
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    //查询数据
    @GetMapping("/book")
    @ResponseBody
    public List<Book> list() {
        //1 构造查询条件
        //1.1 创建查询条件类
        BookExample example = new BookExample();
        //1.2 创建条件构造器
        BookExample.Criteria criteria = example.createCriteria();
        //1.3 通过criteria设置条件
        //...
        
        //2 根据条件查询，如果没有查询条件，传入一个空的example即可
        List<Book> list = bookService.selectByExample(example);
        
        //3 返回结果
        return list;
    }

    //添加数据
    @PostMapping("/book")
    @ResponseBody
    public Book add(@RequestBody Book book) {
        //1 准备数据，例如设置book主键等
        //...
        book.setId((int) (System.currentTimeMillis() % 1000000000));
        
        //2 插入数据
        bookService.insertSelective(book);
        
        //3 把新添加的数据返回给调用者
        return book;
    }

    //修改数据
    @PutMapping("/book")
    @ResponseBody
    public Book update(@RequestBody Book book) {
        //1 准备数据，例如设置book的修改时间等
        //...
        
        //2 更新数据
        bookService.updateByPrimaryKeySelective(book);
        
        //3 把新修改的数据返回给调用者
        return bookService.selectByPrimaryKey(book.getId());
    }

    //删除数据
    @DeleteMapping("/book/{id}")
    @ResponseBody
    public String delete(@PathVariable("id") Integer id) {
        //1 根据主键删除数据
        bookService.deleteByPrimaryKey(id);
        
        //2 返回一个状态码给调用者
        return "200";
    }






}